//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { Button, Form, message, Modal, Select, Table, Tabs } from "antd";
import type { SHARE_TARGET_TYPE, ShareInfo } from "@/api/project_share";
import { get_type_name, create_share, list_share, remove_share } from "@/api/project_share";
import { open as shell_open } from '@tauri-apps/api/shell';
import { writeText } from '@tauri-apps/api/clipboard';
import { request } from "@/utils/request";
import type { ColumnsType } from 'antd/lib/table';
import moment from "moment";
import { get_session } from "@/api/user";
import { ProjectInfo } from "@/api/project";

const PAGE_SIZE = 10;

interface ShareHistoryProps {
    projectInfo: ProjectInfo;
    myUserId: string;
    shareTargetType: SHARE_TARGET_TYPE;
    shareTargetId: string;
    onClick: (shareId: string, shareSecret: string, open: boolean) => void;
}

const ShareHistory = (props: ShareHistoryProps) => {
    const [shareList, setShareList] = useState<ShareInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const loadShareList = async () => {
        const sessionId = await get_session();
        const res = await request(list_share({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            filter_by_target_type: true,
            target_type: props.shareTargetType,
            filter_by_target_id: true,
            target_id: props.shareTargetId,
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        }));
        setShareList(res.share_info_list);
        setTotalCount(res.total_count);
    };

    const removeShare = async (shareId: string) => {
        const sessionId = await get_session();
        await request(remove_share({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            share_id: shareId,
        }));
        await loadShareList();
        message.info("删除成功");
    };

    const columns: ColumnsType<ShareInfo> = [
        {
            title: "名称",
            render: (_, row: ShareInfo) => (
                <a onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    props.onClick(row.share_id, row.share_secret, true);
                }}>{get_type_name(row.target_type)}:{row.target_name}</a>
            ),
        },
        {
            title: "有效期限",
            render: (_, row: ShareInfo) => moment(row.expire_time).format("YYYY-MM-DD HH"),
        },
        {
            title: "操作",
            width: 80,
            render: (_, row: ShareInfo) => (
                <Button type="link" danger style={{ minWidth: 0, padding: "0px 0px" }}
                    disabled={!(row.share_user_id == props.myUserId || props.projectInfo.user_project_perm.can_admin)}
                    onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeShare(row.share_id);
                    }}>删除</Button>
            ),
        }
    ];

    useEffect(() => {
        loadShareList();
    }, [curPage]);

    return (
        <Table rowKey="share_id" dataSource={shareList} columns={columns} scroll={{ y: 300 }}
            pagination={{ current: curPage + 1, pageSize: PAGE_SIZE, total: totalCount, onChange: page => setCurPage(page - 1), hideOnSinglePage: true, showSizeChanger: false }}
        />
    );
};

export interface ShareModalProps {
    projectInfo: ProjectInfo;
    myUserId: string;
    shareTargetType: SHARE_TARGET_TYPE;
    shareTargetId: string;
    shareTitle: string;
    shareWebUrl: string;
    timeDiff: number;
    onClose: () => void;
}

const ShareModal = (props: ShareModalProps) => {
    const [activeKey, setActiveKey] = useState<"share" | "history">("share");
    const [expireDay, setExpireDay] = useState(7);


    const copyShareUrl = async (shareId: string, shareSecret: string, open: boolean) => {
        const shareBaseUrl = props.shareWebUrl;
        if (shareBaseUrl == "") {
            return;
        }
        const url = new URL(shareBaseUrl);
        if (url == null) {
            return;
        }
        url.searchParams.append("id", shareId);
        url.searchParams.append("secret", shareSecret);
        if (open) {
            await shell_open(url.toString());
        }
        await writeText(url.toString());
        message.info("已复制分享链接");
    };

    const createShare = async () => {
        const sessionId = await get_session();
        const expireTime = Date.now() + expireDay * 24 * 3600 * 1000 + props.timeDiff;
        const res = await create_share({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            target_type: props.shareTargetType,
            target_id: props.shareTargetId,
            expire_time: expireTime,
        });
        copyShareUrl(res.share_id, res.share_secret, true);
        props.onClose();
    };

    return (
        <Modal open mask={false} title={`分享${get_type_name(props.shareTargetType)}:${props.shareTitle}`}
            footer={activeKey == "share" ? undefined : null}
            okText="分享"
            bodyStyle={{ padding: "2px 10px" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                createShare();
            }}>
            <Tabs activeKey={activeKey} onChange={key => setActiveKey(key as "share" | "history")}
                type="card"
                items={[
                    {
                        key: "share",
                        label: "分享",
                        children: (
                            <Form>
                                <Form.Item label="有效期限">
                                    <Select value={expireDay} onChange={value => setExpireDay(value)}>
                                        <Select.Option value={1}>1天</Select.Option>
                                        <Select.Option value={3}>3天</Select.Option>
                                        <Select.Option value={7}>1周</Select.Option>
                                        <Select.Option value={14}>2周</Select.Option>
                                        <Select.Option value={28}>4周</Select.Option>
                                    </Select>
                                </Form.Item>
                            </Form>
                        ),
                    },
                    {
                        key: "history",
                        label: "分享记录",
                        children: (
                            <>
                                {activeKey == "history" && (
                                    <ShareHistory projectInfo={props.projectInfo} myUserId={props.myUserId}
                                        shareTargetId={props.shareTargetId} shareTargetType={props.shareTargetType}
                                        onClick={(shareId: string, shareSecret: string, open: boolean) => copyShareUrl(shareId, shareSecret, open)} />
                                )}
                            </>
                        )
                    }
                ]} />
        </Modal>
    );
};

export default ShareModal;